package ezXpns;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * A class that keeps track of the data associated with 
 * each profile
 *
 */

//@author A0088827L
public class Profile {
	public Profile() {
		incomeTypes.addType("One-off");
		incomeTypes.addType("Daily");
		incomeTypes.addType("Monthly");
		incomeTypes.addType("Yearly");
		incomeTypes.addType("Other");
		
		expenseTypes.addType("Cash");
		expenseTypes.addType("Debit");
		expenseTypes.addType("Credit");
		expenseTypes.addType("Cheque");
		expenseTypes.addType("Other");
		
		username = "New User";
		budget = 1000.0f;
		filePath = "assets\\Optimized Icons\\user.png";
	}
	
	public void setBudget(float newBudget){
		budget = newBudget;
	}
	
	public float getBudget() {
		return budget;
	}
	
	public TypeRegistry getIncomeTypes() {
		return incomeTypes;
	}
	
	public TypeRegistry getExpenseTypes() {
		return expenseTypes;
	}
	
	public void save(String path) throws IOException {
		try(FileWriter writer = new FileWriter(path);
			BufferedWriter bw = new BufferedWriter(writer)) {			
			Gson gson = GSON_BUILDER.create();
			bw.write(gson.toJson(this));
			bw.newLine();
		}
	}
	
	public void load(String path) throws FileNotFoundException, IOException {
		try(FileReader reader = new FileReader(path);
			BufferedReader bf = new BufferedReader(reader)) {
			Gson gson = GSON_BUILDER.create();
			Profile profile = gson.fromJson(bf.readLine(), Profile.class);
			
			budget = profile.budget;
			incomeTypes = profile.incomeTypes;
			expenseTypes = profile.expenseTypes;
			username = profile.username;
			
			incomeTypes.addType("Other");
			expenseTypes.addType("Other");
		}
	}

	private float budget;
	private TypeRegistry incomeTypes = new TypeRegistry();
	private TypeRegistry expenseTypes = new TypeRegistry();
	private String username;
	private String filePath; 
	
	private static final GsonBuilder GSON_BUILDER;
	static {
		GsonBuilder builder = new GsonBuilder();
		builder.registerTypeAdapter(TypeRegistry.class, new TypeRegistry.Serializer());
		builder.registerTypeAdapter(TypeRegistry.class, new TypeRegistry.Deserializer());
		GSON_BUILDER = builder;
	}
	
	public void setUsername(String userName){
		this.username = userName;
	}
	public String getUsername() {
		return username;
	}
	public void setFilepath(String filePath){
		this.filePath = filePath;
	}
	public String getFilepath() {
		return filePath;
	}
}
